import React, { useState } from 'react';
import { Button, Drawer, Form, Input, message, Select, Spin } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import UserPhoto from '@/pages/common/UserPhoto';
import { getDictList4Type } from '@/services/system/dict';
import { getRoleSelectData } from '@/services/system/role';
import { getUserId, userUpdate } from '@/services/system/user';

// 定义传参
interface UserEditParams {
  refresh: () => void;
  userId: string;
}

/**
 * 用户编辑
 *
 * @author zhangby
 * @date 28/9/20 5:15 pm
 */
const UserEdit: React.FC<UserEditParams> = (props) => {
  const { children, refresh, userId } = props;
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [userTypeList, setUserTypeList] = useState<API.DictMap[]>();
  const [roleSelectData, setRoleSelectData] = useState<API.DictMap[]>();

  const [form] = Form.useForm();

  // 初始化
  const onPreInit = async () => {
    setVisible(true);
    form.resetFields();
    // 查询数据
    try {
      setLoading(true);
      // eslint-disable-next-line no-shadow
      const userTypeList = await getDictList4Type('user_type');
      if (userTypeList.code === '000') {
        setUserTypeList(userTypeList.result);
      }
      // 查询用户角色
      const roleSelectDataDB = await getRoleSelectData();
      if (roleSelectDataDB.code === '000') {
        setRoleSelectData(roleSelectDataDB.result);
      }
      // 查询用户详情
      const userData = await getUserId(userId);
      if (userData.code === '000') {
        const { result } = userData;
        form.setFieldsValue({ ...result, roleIds: result?.tails.roleIds });
      }
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  };

  // 提交
  const onSubmit = () => {
    form.validateFields().then(async (values) => {
      try {
        setLoading(true);
        const params = { ...values, roleId: values.roleIds.join(',') };
        const data = await userUpdate({ ...params, id: userId });
        if (data.code === '000') {
          message.success('编辑用户成功');
          setVisible(false);
          setLoading(false);
          refresh();
        }
      } catch (e) {
        setLoading(false);
      }
    });
  };

  return (
    <>
      <span style={{ cursor: 'pointer' }} onClick={onPreInit}>
        {children || (
          <Button type="primary" shape="circle">
            <EditOutlined />
          </Button>
        )}
      </span>
      {/* 弹出窗口 */}
      <Drawer
        title="编辑用户"
        placement="right"
        closable={false}
        onClose={() => setVisible(false)}
        visible={visible}
        width={650}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setVisible(false)} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={onSubmit} type="primary">
              确定
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          {/* form 表单 */}
          <Form {...layout} form={form}>
            <Form.Item name="photo" label="" style={{ marginLeft: 280 }}>
              <UserPhoto isEdit size={60} />
            </Form.Item>
            <Form.Item
              name="name"
              label="用户名"
              rules={[{ required: true, message: '用户名不能为空' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="loginName"
              label="登录名"
              rules={[{ required: true, message: '登录名不能为空' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item name="mobile" label="联系方式">
              <Input />
            </Form.Item>
            <Form.Item name="email" label="电子邮箱">
              <Input />
            </Form.Item>
            <Form.Item name="userType" label="用户类型">
              <Select placeholder="选择用户类型">
                {userTypeList?.map((item, key) => (
                  <Option value={item.value} key={key}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="roleIds" label="所属角色">
              <Select placeholder="选择所属角色" mode="multiple">
                {roleSelectData?.map((item, key) => (
                  <Option value={item.value} key={key}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </Spin>
      </Drawer>
    </>
  );
};

const layout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};

export default UserEdit;
